package com.hit.server.comm;

import cn.hutool.core.thread.ThreadUtil;
import com.hit.comm.constants.CommConstants;
import com.hit.comm.netty.MessageDecoder;
import com.hit.comm.netty.MessageEncoder;
import com.hit.comm.netty.TcpServer;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.*;
import io.netty.handler.codec.DelimiterBasedFrameDecoder;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;

import java.util.Optional;
import java.util.concurrent.CompletableFuture;


@Slf4j
@Component
public class NettyServer implements CommandLineRunner {

    @Value("${server.tcp-port:9874}")
    private Integer bindPort;

    @Override
    public void run(String... args) throws Exception {
        CompletableFuture.runAsync(() -> {
            try {
                log.info("启动服务端端口:" + bindPort);
                TcpServer server = new TcpServer("robot-server-comm", bindPort, new ChannelInitializer<Channel>() {
                    @Override
                    protected void initChannel(Channel channel) throws Exception {
                        ByteBuf delimiter = Unpooled.copiedBuffer(CommConstants.DELIMITER.getBytes());
                        channel.pipeline().addLast(new DelimiterBasedFrameDecoder(CommConstants.MAX_LENGTH, delimiter));
                        channel.pipeline().addLast(new MessageDecoder());
                        channel.pipeline().addLast(new MessageEncoder());
                        channel.pipeline().addLast(new NettyServerHandler());
                    }
                });
                ThreadUtil.execAsync(() -> {
                    try {
                        server.bind();
                    } catch (InterruptedException e) {
                        log.error("[robot-server-comm] server bind error", e);
                    }
                });
            } catch (Exception e) {
                log.info("bind() failed" + e.getMessage());
                throw new RuntimeException(e);
            }
        });
    }
}
